package edu.fjut.se1603.yuan.dao.impl;

import edu.fjut.se1603.yuan.dao.BaseDao;
import edu.fjut.se1603.yuan.dao.PetOwnerDao;
import edu.fjut.se1603.yuan.entity.PetOwner;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class PetOwnerDaoImpl extends BaseDao implements PetOwnerDao {


    @Override
    public List<PetOwner> getAllOwner() {
        List<PetOwner> petOwners = null;
        try {
            Statement statement = conn.createStatement();
            ResultSet set = statement.executeQuery("select ID,NAME,MONEY from pet_owner");

            petOwners = new ArrayList<>();
            while (set.next()) {
                int id = set.getInt("ID");
                String name = set.getString("NAME");
                double money = set.getDouble("MONEY");
                petOwners.add(new PetOwner(id, name, money));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return petOwners;
    }

    @Override
    public PetOwner selectOwner(Integer petOwnerId) {
        PetOwner petOwner = null;
        try {
            Statement statement = conn.createStatement();
            ResultSet set = statement.executeQuery("select ID,NAME,MONEY from pet_owner where ID=" + petOwnerId);
            if (set.next()) {
                petOwner = new PetOwner(set.getInt("ID"), set.getString("NAME"), set.getDouble("MONEY"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return petOwner;
    }

    @Override
    public int updateOwnerMoney(Integer petOwnerId, double money) {
        int flag = 0;

        try {
            PreparedStatement preparedStatement = conn.prepareStatement("update pet_owner set MONEY=? where ID=?");
            preparedStatement.setDouble(1, money);
            preparedStatement.setInt(2, petOwnerId);
            flag = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }


    @Override
    public double getOwnerMoney(int petOwnerId) {
        double money = 0;

        try {
            PreparedStatement preparedStatement = conn.prepareStatement("select MONEY from pet_owner where ID=?");
            preparedStatement.setInt(1, petOwnerId);
            ResultSet set = preparedStatement.executeQuery();
            if (set.next()) {
                money = set.getDouble("MONEY");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return money;
    }




}
